package cn.softcits.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-07-11 3:09 PM
 */
public class LockerTest {

    public static void main(String[] args) {

//        locker.readLock().lock();
//
//        locker.readLock().unlock();

        SellTicket st = new SellTicket();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    boolean flag = st.sell(Thread.currentThread().getName());
                    if(flag) {
                        break;
                    }

                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    boolean flag = st.sell(Thread.currentThread().getName());
                    if(flag) {
                        break;
                    }
                }

            }
        }).start();

    }

    public static class SellTicket {
        ReadWriteLock locker = new ReentrantReadWriteLock();
        Integer tickets = 100;

        /**
         *
         * @param name
         * @return
         */
        boolean sell(String name) {
           locker.writeLock().lock();
            if(tickets <= 0) {
                // sold out
                return true;
            }
            System.out.println(name + " selled : " + tickets);
            tickets --;
            locker.writeLock().unlock();
            // not yet
            return false;

        }
    }
}
